var express = require("express");
var router = express.Router();
var mongoose = require('mongoose');
var models = require('./models');

var User = models.User;

//var dbConn = mongoose.connect("mongodb://localhost:27020/makeblock_iot");

router.get('/', function(req, res) {
  console.log('mongodb');
	res.send("mongodb");
});

var board = {
		"boardid1":{
			"type":"row",
			"config":{},
			"boxes":[]
		}
}

var board2 = {
			"type":"row",
			"config":{},
			"boxes":[]
}



router.get('/insert', function(req, res) {
	var userid = {id: 1};
	var update = {userkey: "shansjlin", dashboard: board, modified:new Date};
	var options    = {upsert : true};
	var callback = function(err) {
		if(err) {
			console.log(err);
			res.send(err);
		} else {
			console.log("insert success");
			res.send("insert success");
		}
	}
	User.Insert(userid, update, options, callback);
});

router.get('/delete', function(req, res) {
	var userid = {id: 1};
	var callback = function(err) {
		if(err) {
			console.log(err);
			res.send(err);
		} else {
			console.log("delete success");
			res.send("delete success");
		}
	}
	User.Delete(userid, callback);
});

router.get('/update', function(req, res) {
	var userid = {id: 1};
	var update = {userkey: "linyanwen", dashboard: board, modified:new Date};
	var options    = {upsert : true};
	var callback = function(err) {
		if(err) {
			console.log(err);
			res.send(err);
		} else {
			console.log("update success");
			res.send("update success");
		}
	}
	User.Update(userid, update, options, callback);
});

router.get('/query', function(req, res) {
	var userid = {id: 1};
	var callback = function(err, iRet) {
		if(err) {
			console.log(err);
			res.send(err);
		} else {
			console.log(iRet);
			res.send(iRet);
		}
	}
	new User({}).Query(userid, callback);
});

router.get('/findandupdate', function(req, res) {
	var userid = {id: 1};
	var callback = function(err, iRet) {
		if(err) {
			console.log(err);
			res.send(err);
		} else {
			if(iRet != null) {
				iRet.dashboard["board2"] = board2;
				var update = {dashboard: iRet.dashboard, modified:new Date};
				var options    = {upsert : true};
				User.Update(userid, update, options, function(err) {
					if(err) {
						console.log(err);
					}
				});
				console.log(iRet);
				res.send(iRet);
			} else {
				console.log("cannot find record");
				res.send("cannot find record");
			}
		}
	}
	new User({}).Query(userid, callback);
});

/*
app.get('/INSERT', function(req, res) {
	var user = new User({
		id: 1,
		userkey: "shansjlin",
		dashboard: board
	});
	user.save();
	res.send("addUser success");
});
*/

module.exports = router;
